package com.company.planner.web.screens.hotwords;

import com.company.planner.entity.HotOperationRecord;
import com.company.planner.entity.HotWords;
import com.company.planner.entity.NodeState;
import com.company.planner.entity.OperationState;
import com.company.planner.service.WordsService;
import com.haulmont.cuba.core.global.DataManager;
import com.haulmont.cuba.gui.components.HasValue;
import com.haulmont.cuba.gui.components.ValidationErrors;
import com.haulmont.cuba.gui.screen.*;
import org.slf4j.Logger;

import javax.inject.Inject;

@UiController("planner_HotWords.edit")
@UiDescriptor("hot-words-edit.xml")
@EditedEntityContainer("hotWordsDc")
@LoadDataBeforeShow
public class HotWordsEdit extends StandardEditor<HotWords> {
    @Inject
    private DataManager dataManager;
    @Inject
    private WordsService wordsService;
    @Inject
    private Logger log;

    private String sourceWord;


    @Subscribe
    public void onValidation(ValidationEvent event) {
        HotWords hotWords = getEditedEntity();
        if (!hotWords.getWord().equals(sourceWord)) {
            boolean existRecords = wordsService.existWordsOperationRecords(hotWords);
            if (existRecords) {
                HotOperationRecord record = dataManager.create(HotOperationRecord.class);
                record.setNodeState(NodeState.BEGIN);
                record.setOperationState(OperationState.UPDATE);
                record.setWord(hotWords);
                record.setWords(hotWords.getWord());
                record.setSourceWords(sourceWord);
                dataManager.commit(record);
            } else {
                event.addErrors(ValidationErrors.of("有未执行的修改词语流水单"));
            }
        }
    }


    @Subscribe("wordField")
    public void onWordFieldValueChange(HasValue.ValueChangeEvent<String> event) {
        HotWords sourceWords = dataManager.load(HotWords.class)
                .id(getEditedEntity().getId())
                .one();
        sourceWord = sourceWords.getWord();
        log.info("sourceWords word:{}", sourceWords.getWord());
        log.info("change word:{}", event.getValue());
    }


}